package com.gack.netty.clientTest;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 
* @ClassName: NettyClient 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author (ZhangXinYu)  
* @date 2018年8月30日 下午4:37:51 
* @version V1.0
 */
public class NettyClient {
	private String HOST;
	private int PORT;
	private EventLoopGroup bossGroup ;
	private EventLoopGroup workerGroup ;
	private Bootstrap bootstrap;
	ChannelFuture future = null;
	public NettyClient(String host,int port) {
		this.HOST = host;
		this.PORT = port;
		bossGroup = new NioEventLoopGroup();
		workerGroup = new NioEventLoopGroup();
	}
	
	public void run() throws Exception{
		
		bootstrap = new Bootstrap();
		bootstrap.group(workerGroup)
			.channel(NioSocketChannel.class)
			.option(ChannelOption.SO_KEEPALIVE, true)
			.handler(new NettyClientInitializer(this));
		future = bootstrap.connect(this.HOST,this.PORT).addListener(new ConnectionListener(this)).sync();
		System.out.println("客户端启动成功,已连接服务器[" + this.HOST + ":" + this.PORT + "]");
	}
	
	public void close(){
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
		future.channel().closeFuture().syncUninterruptibly();
	}
	
	public static void main(String[] args) throws Exception{
		new NettyClient("127.0.0.1", 9090).run();
//		new NettyClient("123.207.172.107", 9090).run();
	}
}
